package com.appheader.rongmaphone.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.appheader.rongmaphone.R;
import com.appheader.rongmaphone.cache.file.ResourceFileManager;
import com.appheader.rongmaphone.cache.preference.PreferenceUtil;
import com.appheader.rongmaphone.constants.GlobalVars;
import com.appheader.rongmaphone.entity.Project;
import com.appheader.rongmaphone.entity.ProjectEntity;
import com.appheader.rongmaphone.user.UserInfo;
import com.appheader.rongmaphone.utils.CompressFile;
import com.appheader.rongmaphone.utils.MD5;
import com.appheader.rongmaphone.utils.json.JSONUtil;
import com.appheader.rongmaphone.utils.network.DownloadUtil;
import com.appheader.rongmaphone.utils.network.HttpUtil;
import com.zxing.activity.CaptureActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ScanActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int DOWNLOAD_FINISH = 1;
    private static final int REQUEST_CODE = 0;
    private PreferenceUtil preferenceUtil;
    private Map<Integer, String> scanMap = new HashMap<>();
    private String uid;
    private int Num = 1;
    private String projectId;
    private TextView loadingText, downText;
    private RelativeLayout scanBottomText;
    private LinearLayout progressLayout;
    private Button onLineText, downLoadText;
    private TextView scanName;
    private ImageView restartImage;
    private static Map<Integer, String> map = new HashMap<>();
    private String TAG = "ScanActivity";
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DOWNLOAD_FINISH:
                    if (loadingText != null) {
                        loadingFinish.setVisibility(View.VISIBLE);
                        loadingText.setVisibility(View.GONE);
//                        scanBottomText.setVisibility(View.VISIBLE);
                    }
                    break;
            }
        }
    };
    private TextView loadingFinish;
    private String pageType;
    private String fileMD5;
    boolean isSave = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        try {
            setContentView(R.layout.activity_scan);
            initView();
            preferenceUtil = new PreferenceUtil(getApplicationContext());
            String userStr = preferenceUtil.getString("userStr");
            preferenceUtil.putInt("width",getWindow().getWindowManager().getDefaultDisplay().getWidth());
            preferenceUtil.putInt("",getWindow().getWindowManager().getDefaultDisplay().getWidth());
            UserInfo userInfo = JSONUtil.userInfos(userStr);
            uid = userInfo.getUid();

            //生成md5文件
            String path = ResourceFileManager.createOrGetUserProfileDir(uid) + File.separator + "previewZip.zip";
            Log.e("SCAN", "onResponse: ------------" + path);
            File file = new File(path);
            if (!file.exists()) {
                fileMD5 = "";
            }else {
                fileMD5 = MD5.getFileMD5(file);
            }
            //生成文件的md5
//            fileMD5 = MD5.getFileMD5(file);
            Log.e("MD5", "onResponse: " + fileMD5);

            Intent intent = getIntent();
            String result = intent.getStringExtra("result");
//            projectId = intent.getStringExtra("projectId");
//            String review = intent.getStringExtra("review");
//            String name = intent.getStringExtra("name");
            Log.e("SCANTAG", "onCreate: " + result);
            projectId = ResourceFileManager.splitScanUrlPath(result);
            String reviewStr = splitandUrl(result, 2);
            String review = reviewStr.substring(reviewStr.lastIndexOf("=") + 1);
            String splitBy = splitByUrl(result, 4);
            String name = splitandUrl(splitBy, 0);
            String splitByType = splitByUrl(result, 2);
            pageType = splitandUrl(splitByType, 0);

            Log.e("ProjectId", "onActivityResult: ---" + projectId + "==" + reviewStr + "---" + review + "--" + name + "--" + pageType);
            try {
                String decode = URLDecoder.decode(name, "UTF-8");
                scanName.setText(decode + "");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            setListener();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    private void setListener() {
        onLineText.setOnClickListener(this);
        downLoadText.setOnClickListener(this);
        restartImage.setOnClickListener(this);
    }
    private void initView() {
        loadingText = (TextView) findViewById(R.id.loading_text);
        loadingFinish = (TextView) findViewById(R.id.loading_text_finish);
        scanBottomText = (RelativeLayout) findViewById(R.id.scan_bottom_text);
        onLineText = (Button) findViewById(R.id.online_text);
        downLoadText = (Button) findViewById(R.id.download_text);
        scanName = (TextView) findViewById(R.id.scan_name_text);
        restartImage = (ImageView) findViewById(R.id.restart_scan_img);
        progressLayout = (LinearLayout) findViewById(R.id.linearLayout);
    }

    public synchronized void add(int totle, final String uid, final String projectId, String picId, String name, String lastModifyTime, String pageType,boolean isOnline) {
        Num++;
        Log.i("SSS", "T" + Thread.currentThread().getName());
        Log.i("SSS", "T" + Num + "----" + totle);
        Log.e(TAG, "add: --------isOnline------"+isOnline);
        if (Num == totle) {
            List<Project> projects = DataSupport.findAll(Project.class);
            for (int i = 0; i < projects.size(); i++) {
                String prjectId = projects.get(i).getPrjectId();
                if (prjectId.equals(projectId)){
                    isSave = true;
                    break;
                }else {
                    isSave = false;
                }
            }
            Intent intent1 = new Intent(ScanActivity.this, ContentActivity.class);
            if (!isSave&&!isOnline){
                Project project = new Project();
                project.setIsDownLoad("true");
//            project.setLastModifyTime();
                project.setPrjectId(projectId);
                project.setPicId(picId);
                project.setName(name);
                project.setPageType(pageType);
                project.setCreator(uid);
                boolean save = project.save();
                Log.e("SCANSAVE", "add: " + save);//存进去了
                intent1.putExtra("isOnline",false);
            }else {
                intent1.putExtra("isOnline",true);
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            handler.sendEmptyMessage(DOWNLOAD_FINISH);
            intent1.putExtra("uid", uid);
            intent1.putExtra("projectId", projectId);
            intent1.putExtra("review", "review");
            intent1.putExtra("pageType", pageType);
            Log.e("INTENT", "onItemClick: " + projectId);
            Log.e(TAG, "onClick: " + uid + "----------------------" + projectId);
            startActivity(intent1);
            overridePendingTransition(0,0);
            finish();
        }
    }
    private void getData(final String projectId, String fileMD5, final String pageType, final boolean isOnline) {
        HttpUtil.getCloudContentOkHttpClient(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("SCANRESPONSE", "onResponse: " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                    String jsonStr = jsonObject1.toString();
                    Boolean needDownload = jsonObject1.getBoolean("needDownload");
                    ProjectEntity.DataEntity projectEntity = new ProjectEntity.DataEntity();
                    projectEntity.setNeedDownload(needDownload);
                    Log.e("SCANDATA", "onResponse: " + jsonStr);
                    Log.e("SCANTAG", "needDownload" + needDownload);
                    preferenceUtil.putBoolean("needDownload", needDownload);
                    preferenceUtil.putString("jsonData", jsonStr);
                    JSONObject jsonObject2 = jsonObject1.getJSONObject("project");
                    String picId = jsonObject2.getString("picId");
                    JSONArray resList = jsonObject1.getJSONArray("resList");
                    String name = jsonObject2.getString("name");
                    String lastModifyTime = jsonObject2.getString("lastModifyTime");
//                    preferenceUtil.putString("project", jsonObject2.toString());
                    preferenceUtil.putString("name", name);
                    preferenceUtil.putString("picId", picId);
                    preferenceUtil.putString("lastModifyTime", lastModifyTime);
                    Map<Integer, String> map1 = new HashMap<Integer, String>();
                    for (int i = 0; i < resList.length(); i++) {
                        String aa = resList.getString(i);
                        Log.e("scaniiiiii", "onResponse: " + aa);
                        map1.put(i, aa);
                    }
                    map.putAll(map1);
                    //存储方案的json文件,成功
                    String jsonPath = ResourceFileManager.createOrGetUserProfileDir(uid) + File.separator + projectId;

                    File file = new File(jsonPath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    File filePath = new File(jsonPath + "/" + projectId + ".json");
                    if (!filePath.exists()) {
                        filePath.createNewFile();
                        FileOutputStream fos = new FileOutputStream(filePath);
                        fos.write(jsonStr.getBytes());
                        fos.close();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, projectId, fileMD5, "");
        Boolean needDownload = preferenceUtil.getBoolean("needDownload");
        String data = preferenceUtil.getString("jsonData");
        final String picId = preferenceUtil.getString("picId");
        final String name = preferenceUtil.getString("name");
        final String lastModifyTime = preferenceUtil.getString("lastModifyTime");
//        String project = preferenceUtil.getString("project");
//        Log.e("SCANneedDownload", "onItemClick: " + needDownload +map.size()+ "=====" + project);
        //okhttp发送get请求下载zip包成功
        Log.e("data", "getData: -----" + data);
        Log.e("needdownload", "getData: " + needDownload);
        Log.e("name", "getData: " + name);
        Log.e("lastModifyTime", "getData: " + lastModifyTime);
        if (needDownload) {
            HttpUtil.getZipOkHttpClient(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    int downLoadFileSize = 0;
                    String sdcardRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + GlobalVars.getPackageInfo().packageName + "/download" + File.separator + uid;
                    Log.e("TAG", "onResponse:++++++++++++++++ " + sdcardRoot);
                    File rootDir = new File(sdcardRoot);
                    //创建目录
                    if (!rootDir.exists()) {
                        boolean is = rootDir.mkdirs();
                        Log.e("IS", "onResponse: ---" + is);
                    }
//                //下载后的文件名
                    String filePath = sdcardRoot + File.separator + "previewZip.zip";
                    File file = new File(filePath);
                    if (file.exists()) {
                        file.delete();
                    }
                    InputStream inputStream = response.body().byteStream();
                    long total = response.body().contentLength();
                    Log.e("TOTAL", "onResponse: " + total);
                    long sum = 0;
                    int len = 0;
                    byte[] buf = new byte[2048];
                    FileOutputStream fos = new FileOutputStream(filePath);
                    while ((len = inputStream.read(buf)) != -1) {
                        downLoadFileSize += len;
                        fos.write(buf, 0, len);
                        Log.e("zipdonwload", "downloadFile: " + downLoadFileSize);
                        fos.flush();
                    }
                    inputStream.close();
                    fos.close();
                    //解压
                    CompressFile.unZipFileAndOpenNewPage(uid);
                }
            });
        }
        //再睡一秒
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.e("mapsize", "getData: " + map.size());
//        if (map.size() > 0) {
        for (int i = 0; i < map.size(); i++) {
            final String aa = map.get(i);
            final int fileTotalNum = map.size();//文件个数
            Log.e("Stringaa", "onItemClick: " + i + aa);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.e("TAG", "run:+++++ " + aa);
                    final String paths;
                    final String dirPath;
                    int downLoadFileSize = 0;
                    if (aa.indexOf("http:") != -1) {//说明存在http://请求协议头
                        String urlPath = ResourceFileManager.splitImgUrlPath(aa).substring(
                                ResourceFileManager.splitImgUrlPath(aa).lastIndexOf("/") + 1);
                        Log.e("TAG---", "run: " + urlPath);
                        String dir1 = splitUrl(aa, 3);//
                        String dir2 = splitUrl(aa, 4);
                        String resource = splitUrl(aa, 5);
                        paths = dir1 + "/" + dir2 + "/" + resource + "/" + urlPath;//全路径
                        dirPath = dir1 + "/" + dir2 + "/" + resource;
                    } else {
                        String urlPath = ResourceFileManager.splitImgUrlPath(aa).substring(
                                ResourceFileManager.splitImgUrlPath(aa).lastIndexOf("/") + 1);
                        Log.e("TAG+++", "run: " + urlPath);
//                        dirPath = ResourceFileManager.splitDirPath(aa).substring(ResourceFileManager.splitDirPath(aa).lastIndexOf("/") + 1);
                        String dir1 = splitUrl(aa, 1);//uid
                        //方案
                        String dir2 = splitUrl(aa, 2);
                        //页名
                        String pageId = splitUrl(aa, 3);
                        paths = dir1 + "/" + dir2 + "/" + pageId + "/" + urlPath;
                        dirPath = dir1 + "/" + dir2 + "/" + pageId;
                    }
                    Log.e("TAGpath", "path= ====" + paths);
                    Log.e("TAGdirPath", "dirPath= ---" + dirPath);
                    try {
                        URL url = null;
                        if (aa.indexOf("http:") != -1) {
                            url = new URL(aa);
                        } else {
                            url = new URL("http://" + aa);
                        }
                        try {
                            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                            urlConnection.setConnectTimeout(5000);
                            if (urlConnection.getResponseCode() != 200){
                                ++Num;
                                throw new RuntimeException("请求url失败");
                            }
                            urlConnection.connect();
                            int totalLen = urlConnection.getContentLength();
                            Log.e("TAG", "run: " + totalLen);
                            String sdcardRoot = Environment.getExternalStorageDirectory().getAbsolutePath()
                                    + File.separator
                                    + GlobalVars.getPackageInfo().packageName
                                    + "/download"
                                    + File.separator;
                            File rootDir = new File(sdcardRoot + dirPath);
                            //创建目录
                            if (!rootDir.exists()) {
                                boolean is = rootDir.mkdirs();
                                Log.e("IS", "onResponse: ---" + is);
                            }
                            //文件全路径
                            String filePath = sdcardRoot + paths;
                            File file = new File(filePath);
                            if (file.exists()) {
                                file.delete();
                            }
                            //保存指定的json文件路径
                            InputStream inputStream = urlConnection.getInputStream();
                            byte[] buf = new byte[1024];
                            int len = 0;
                            FileOutputStream fos = new FileOutputStream(filePath);
                            while ((len = inputStream.read(buf)) != -1) {
                                downLoadFileSize += len;
                                fos.write(buf, 0, len);
                                Log.e("RESOURCE", "ImageDownLoad: " + downLoadFileSize);
                                if (downLoadFileSize == totalLen) {
                                    Log.e("FINISH", "run: =========" + true);
                                    add(fileTotalNum, uid, projectId, picId, name, lastModifyTime, pageType,isOnline);
                                }
                                fos.flush();
                            }
                            inputStream.close();
                            fos.close();
                            urlConnection.disconnect();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e(TAG, "run: error=====" + e.getMessage() + aa + "Num=" + (++Num));

                    }
                }
            }).start();
        }
//        }
        String sdcardRoot = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator
                + GlobalVars.getPackageInfo().packageName
                + "/download"
                + File.separator + uid + "/" + projectId + "/" + projectId + ".json";
        //下载每页的json文件到本地
        DownloadUtil.pageJsonDownLoad(uid, sdcardRoot, projectId);

    }

    private String splitUrl(String url, int i) {
        String[] split = url.split("/");
        return split[i];
    }

    public String splitandUrl(String url, int i) {
        if (url != null) {

            String[] split = url.split("&");
            return split[i];
        }
        return null;
    }

    public String splitByUrl(String url, int i) {
        if (url != null) {
            String[] split = url.split("=");
            return split[i];
        }
        return null;
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.online_text://在线浏览,调的是网络的
                progressLayout.setVisibility(View.VISIBLE);
                scanBottomText.setVisibility(View.GONE);
                loadingText.setVisibility(View.VISIBLE);
                getData(projectId, fileMD5, pageType,true);
                break;
            case R.id.download_text://在线下载
                loadingText.setVisibility(View.VISIBLE);
                progressLayout.setVisibility(View.VISIBLE);
                scanBottomText.setVisibility(View.GONE);
                getData(projectId, fileMD5, pageType,false);
                break;
            case R.id.restart_scan_img://重新扫描
                Toast.makeText(ScanActivity.this,"扫描",Toast.LENGTH_SHORT).show();
//                Log.e(TAG, "onClick: ----------点击了" );
                Intent intent = new Intent(ScanActivity.this, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            //这个result是给定的不能随便写
            String result = data.getExtras().getString("result");
            if (!TextUtils.isEmpty(result)) {
                Log.i("AAAAA", "scanactivity" + result);
                String urlHost = "";
                try {
                    urlHost = new URL(result).getHost();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                Log.e("getHost", "onActivityResult: ----" + urlHost);
                if (urlHost.equals("www.armyhorse.com")) {
                    //如果与本公司域名相同，则进入详情下载页面
                    Log.e("--getHost", "onActivityResult: ----" + urlHost);
//                    try {
//                        Thread.sleep(1000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    Intent intent = new Intent(MainActivity.this, ScanActivity.class);
//                    intent.putExtra("result", result);
//                    startActivity(intent);
                    projectId = ResourceFileManager.splitScanUrlPath(result);
                    String reviewStr = splitandUrl(result, 2);
                    String review = reviewStr.substring(reviewStr.lastIndexOf("=") + 1);
                    String splitBy = splitByUrl(result, 4);
                    String name = splitandUrl(splitBy, 0);
                    String splitByType = splitByUrl(result, 2);
                    pageType = splitandUrl(splitByType, 0);

                    Log.e("ProjectId", "onActivityResult: ---" + projectId + "==" + reviewStr + "---" + review + "--" + name + "--" + pageType);
                    try {
                        String decode = URLDecoder.decode(name, "UTF-8");
                        scanName.setText(decode + "");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                } else {
                    //不同，则提示二维码无效
                    Toast.makeText(ScanActivity.this, "获取无效", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
